//
//  TradeViewController.m
//  BTCoin
//
//  Created by Robin on 29/03/2018.
//  Copyright © 2018 Robin. All rights reserved.
//

#import "TradeViewController.h"
#import "AlertFactory.h"
#import "UIAlertController+Block.h"
#import "TradeService.h"
#import "TradeHeaderView.h"
#import "TradeCNYView.h"
#import "TradeControlModel.h"
#import "LoginViewController.h"
#import "TradeCoinModel.h"
#import "CommonPickView.h"
#import "EntrustInfoModel.h"
#import "GlobalData.h"
#import "TradeMenuView.h"
#import "TradePriceSocketModel.h"

typedef NS_ENUM(NSInteger,CommonPickerType) {
    CommonPickerCNYBuy,
    CommonPickerCNYSell,
    CommonPickerBTCBuy,
    CommonPickerBTCSell
};

@interface TradeViewController ()<TradeCNYViewDelegate,TradeMenuViewDelegate>
@property (nonatomic,strong) TradeHeaderView * tradeHeaderView;
@property (nonatomic,strong) TradeMenuView * menuView;
@property (nonatomic,strong) TradeCNYView * CNYView;
@property (nonatomic,strong) TradeControlModel * cnyCtrModel;
@property (nonatomic,strong) GlobalData * gData;
@end

@implementation TradeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setLineHidden:YES];
    self.cnyCtrModel = [[TradeControlModel alloc] init];
    self.gData = [GlobalData sharedGlobalData];
    
    [self initUIHead];
    
    [self addNotification];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenToLogin:) name:LISTENTOAPPLOGINNOTIFICATION object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requsetCNYProxyService) name:REQUESTCNYPROXYNOTIFICATION object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requsetCNYDealService) name:REQUESTCNYDEALNOTIFICATION object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginApp) name:REQUESTLOGINAPPNOTIFICATION object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTradeType) name:UPDATECNYTRADETYPENOTIFICATION object:nil];
}

- (void)initUIHead {
    @WeakObj(self)
    
    self.tradeHeaderView = [[TradeHeaderView alloc] init];
    self.tradeHeaderView.backgroundColor = [UIColor clearColor];
    [self.headView addSubview:self.tradeHeaderView];
    [self.tradeHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.headView).offset(-3);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(30);
        make.centerX.equalTo(self.headView);
    }];
    
    self.tradeHeaderView.block = ^() {
        @StrongObj(self);
        self.menuView.hidden = !self.menuView.hidden;
    };
    
    CGRect viewRect = Rect(0, CGRectGetMaxY(self.headView.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(self.tradeHeaderView.frame) - TabBarHeight);
    
    self.CNYView = [[TradeCNYView alloc] initWithFrame:viewRect];
    self.CNYView.delegate = self;
    self.CNYView.model = self.cnyCtrModel;
    [self.view addSubview:self.CNYView];
    
    self.menuView = [[TradeMenuView alloc] initWithFrame:viewRect];
    self.menuView.delegate = self;
    self.menuView.hidden = YES;
    [self.view addSubview:self.menuView];
    
    [self requestLiveDataByType:USDT region:USDT];
}

#pragma mark - service
- (void)requestLiveDataByType:(NSString *)t region:(NSString *)r {
    NSInteger symbol = -1;
    if ([r isEqualToString:USDT]) {
        if ([t isEqualToString:USDT]) {
            symbol = 1;//USDT
        } else if ([t isEqualToString:LTC]) {
            symbol = 2;
        } else if ([t isEqualToString:ETH]) {
            symbol = 3;
        } else if ([t isEqualToString:ETC]) {
            symbol = 4;
        }
    }
    
    NSDictionary * parDict = @{@"symbol":@(symbol)
                               };
    
    [[TradeService sharedTradeService] realorder:parDict success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            TradePriceSocketModel * model = [[TradePriceSocketModel alloc] initWithDictionary:responseObject error:nil];
            [[TradePriceSocketModel sharedTradePriceSocketModel] updateData:model];
            
             [[NSNotificationCenter defaultCenter] postNotificationName:TRADEPRICESOCKETNOTIFICATION object:nil];
        }
    } fail:^(NSError *error) {
        
    }];
    
}

- (void)requsetCNYProxyService {
    
    NSDictionary * parDict = @{@"symbol":@([self.cnyCtrModel.buyModel getTradeSymbol]),
                               @"status":@(0),
                               @"currentPage":@(1),
                               };
    
    [[TradeService sharedTradeService] entrust:parDict success:^(id responseObject) {
        Loading_Hide(self.view);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            EntrustInfoModel * userInfo = [[EntrustInfoModel alloc] initWithDictionary:responseObject error:nil];
            
            if (SuccessCode == userInfo.code) {
                self.cnyCtrModel.tradeProxyArray = [NSMutableArray arrayWithArray:userInfo.fentrusts];
            } else {
                [PopupViewHUD showErrorPopup:userInfo.msg];
            }
            
            [self.CNYView updateProxyView];
        }
    } fail:^(NSError *error) {
        Loading_Hide(self.view);
    }];
}

- (void)requsetCNYDealService {
    NSDictionary * parDict = @{@"symbol":@([self.cnyCtrModel getCurrentTradeCoinType]),
                               @"status":@(1),
                               @"currentPage":@(1),
                               };
    
    [[TradeService sharedTradeService] entrust:parDict success:^(id responseObject) {
        Loading_Hide(self.view);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            EntrustInfoModel * userInfo = [[EntrustInfoModel alloc] initWithDictionary:responseObject error:nil];
            
            if (SuccessCode == userInfo.code) {
                self.cnyCtrModel.tradeDealArray = [NSMutableArray arrayWithArray:userInfo.fentrusts];
            } else {
                [PopupViewHUD showErrorPopup:userInfo.msg];
            }
            
            [self.CNYView updateDealView];
        }
    } fail:^(NSError *error) {
        Loading_Hide(self.view);
    }];
}

- (void)requsetCNYBuyService:(NSString *)pwd {
    if ([pwd trim].length == 0) {
        [PopupViewHUD showErrorPopup:@"交易密码不能为空!"];
        return;
    }
    Loading_Pig_Show(self.view);
    NSDictionary * parDict = @{@"limited":@(0),
                               @"symbol":@([self.cnyCtrModel.buyModel getTradeSymbol]),
                               @"tradeAmount":@(self.cnyCtrModel.buyModel.number),
                               @"tradeCnyPrice":@(self.cnyCtrModel.buyModel.price),
                               @"tradePwd":[pwd trim]
                               };
    [[TradeService sharedTradeService] buyBtcSubmit:parDict success:^(id responseObject) {
        Loading_Hide(self.view);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            BaseModel * userInfo = [[BaseModel alloc] initWithDictionary:responseObject error:nil];
            
            [UIAlertController createAlertViewWithTitle:@"" withViewController:self withCancleBtnStr:@"取消" withOtherBtnStr:@"确定" withMessage:userInfo.msg completionCallback:nil];
        }
    } fail:^(NSError *error) {
        Loading_Hide(self.view);
    }];
}

#pragma mark - TradeCNYViewDelegate
- (void)CNYbuyAction {
    if (![UserInfo isLogin]) {
        [self loginApp];
    } else {
        [AlertFactory createPassswordAlert:self block:^(NSString *pwd) {
            [self requsetCNYBuyService:pwd];
        }];
    }
}

#pragma mark - TradeMenuViewDelegate
- (void)tradeType:(NSString*)type region:(NSString *)r {
    [self requestLiveDataByType:type region:r];
    [self.CNYView updateBuyTypeView:type region:r];
}

#pragma mark - event actions
- (void)listenToLogin:(NSNotification *)sender {
    BOOL isLogin = [UserInfo sharedUserInfo].bIsLogin;
    if (isLogin) {
        if (self.gData.tradeCNYTypeArray.count == 0) {
            [self.gData requestTradeType:kCoinTypeCNY];
            [self.gData requestTradeType:kCoinTypeBTC];
        } else {
            [self.cnyCtrModel.tradeDealArray addObjectsFromArray:self.gData.tradeCNYTypeArray];
//            [self.CNYView updateBuyTypeView:self.cnyCtrModel.tradeTypeArray[0]];
            self.cnyCtrModel.currentTradeType = self.cnyCtrModel.tradeTypeArray[0];
            
            [self requsetCNYProxyService];
            [self requsetCNYDealService];
        }
    }
}

- (void)loginApp {
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)updateTradeType {
    [self.cnyCtrModel.tradeTypeArray addObjectsFromArray:self.gData.tradeCNYTypeArray];
//    [self.CNYView updateBuyTypeView:self.cnyCtrModel.tradeTypeArray[0]];
    self.cnyCtrModel.currentTradeType = self.cnyCtrModel.tradeTypeArray[0];
}


@end
